package com.zky.seckillzky.seckill.controller;

import com.zky.seckillzky.seckill.entity.UserEntity;
import com.zky.seckillzky.seckill.redis.GoodsKey;
import com.zky.seckillzky.seckill.redis.RedisService;
import com.zky.seckillzky.seckill.service.GoodsService;
import com.zky.seckillzky.seckill.service.impl.UserServiceImpl;
import com.zky.seckillzky.seckill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 这个是商品表
 *
 * @author zky
 * @email zhongkaiyue@gmail.com
 * @date 2021-07-02 11:18:02
 */
@Controller
@RequestMapping("seckill/goods")
public class GoodsController {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RedisService redisService;


    //商品列表页面
//    @RequestMapping(value="/to_list")
//    public String toList(@CookieValue(value = UserServiceImpl.COOKIE_NAME_TOKEN,required = false)String cookieToken
//    , @RequestParam(value = UserServiceImpl.COOKIE_NAME_TOKEN,required = false) String requestToken, Model model
//                         ) {
//
//        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(requestToken)){//都为空直接跳转到登录页面
//            return "login";
//        }
//
//        String token = StringUtils.isEmpty(cookieToken)?requestToken:cookieToken;
//
//           UserEntity user =   userService.getUserByToken(token);
//           model.addAttribute("user",user);
//        return "goods_list";
//    }

//qps 不访问数据库 2387多
//访问数据库 10000次请求 787.9  5000次请求 674
//优化后 redis  5000访问量 循环5次 测压 3198  10000访问量 1659  有时可以上2000  优化后5000 1216访问量
    @RequestMapping(value="/to_list",produces = "text/html")
    @ResponseBody
    public String toList(UserEntity userEntity,Model model, HttpServletRequest request,HttpServletResponse response) {

        if(userEntity==null){
           return  "login";
        }

        //3 从缓存里面取页面数据
        String html = redisService.get(GoodsKey.getGoodsListKey, "", String.class);
        //4判断如果有数据直接返回
        if (!StringUtils.isEmpty(html)){
            return html;
        }
        //5 如果缓存没有数据，从数据库 查询商品列表数据
        //查询商品数据
        List<GoodsVo> goods = goodsService.queryGoods();
        model.addAttribute("goodsList",goods);

        //6 把查询出来的数据渲染成html字符串
        IWebContext ctx =new WebContext(request,response,
                request.getServletContext(),request.getLocale(),model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);

        //7 如果html不为空 把html保存到reids里面，注意保持时间为60秒
        if (!StringUtils.isEmpty(html)){
            redisService.set(GoodsKey.getGoodsListKey,"",html);
        }

        return html;
    }

    /**
     * 商品的详情页面
     * @author zky
     */
    @RequestMapping(value="/to_detail/{goodsId}",produces = "text/html")
    @ResponseBody
    public String toDetail(UserEntity userEntity, Model model, @PathVariable("goodsId")Long goodsId,
                           HttpServletRequest request,HttpServletResponse response) {//130
        if(userEntity==null){
            return  "login";
        }

        String html = redisService.get(GoodsKey.getGoodsDetailKey, "", String.class);


        if (!StringUtils.isEmpty(html)){
            return html;
        }

        //提示：四个参数 user goods 秒杀状态miaoshaStatus、剩余时间（毫秒）

        GoodsVo goods = goodsService.queryGoodsByGoodsId(goodsId);

        int miaoshaStatus=0;//秒杀倒计时  秒杀进行中  秒杀已结束

        long start = goods.getStartTime().getTime();//开始时间
        long end = goods.getEndTime().getTime();//结束时间
        long now = System.currentTimeMillis();//系统当前时间
        long remainSeconds =0;//秒杀开始的剩余时间
        if (now<start){//未开始
            miaoshaStatus=0;
            remainSeconds=(start-now)/1000;
        }else if (now>end){//秒杀结束
            miaoshaStatus=2;
            remainSeconds=-1;
        }else {//秒杀正在进行中
            miaoshaStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("goods",goods);
        model.addAttribute("user",userEntity);
        model.addAttribute("miaoshaStatus",miaoshaStatus);
        model.addAttribute("remainSeconds",remainSeconds);


        //6 把查询出来的数据渲染成html字符串
        IWebContext ctx =new WebContext(request,response,
                request.getServletContext(),request.getLocale(),model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        //7 如果html不为空 把html保存到reids里面，注意保持时间为60秒
        if (!StringUtils.isEmpty(html)){

            redisService.set(GoodsKey.getGoodsDetailKey,"",html);
        }

        return "goods_detail";
    }






//    @RequestMapping(value="/to_detail/{goodsId}")
//    @ResponseBody
//    public R toDetail(UserEntity userEntity, Model model, @PathVariable("goodsId")Long goodsId) {//130
//        if(userEntity==null){
//            return  R.ok().put("error","登录信息失效");
//        }
//
//
//        //提示：四个参数 user goods 秒杀状态miaoshaStatus、剩余时间（毫秒）
//
//        GoodsVo goods = goodsService.queryGoodsByGoodsId(goodsId);
//
//        int miaoshaStatus=0;//秒杀倒计时  秒杀进行中  秒杀已结束
//
//        long start = goods.getStartTime().getTime();//开始时间
//        long end = goods.getEndTime().getTime();//结束时间
//        long now = System.currentTimeMillis();//系统当前时间
//        long remainSeconds =0;//秒杀开始的剩余时间
//        if (now<start){//未开始
//            miaoshaStatus=0;
//            remainSeconds=(start-now)/1000;
//        }else if (now>end){//秒杀结束
//            miaoshaStatus=2;
//            remainSeconds=-1;
//        }else {//秒杀正在进行中
//            miaoshaStatus=1;
//            remainSeconds=0;
//        }
//
//
//        GoodsDetailVo goodsDetailVo = new GoodsDetailVo(miaoshaStatus,remainSeconds,goods,userEntity);
//
//
//        return R.ok().put("success",goodsDetailVo);
//    }




//    @RequestMapping(value="/to_detail/{goodsId}")
//    public String toDetail(UserEntity userEntity, Model model, @PathVariable("goodsId")Long goodsId) {
//        if(userEntity==null){
//            return  "login";
//        }
//
//        //提示：四个参数 user goods 秒杀状态miaoshaStatus、剩余时间（毫秒）
//
//        GoodsVo goods = goodsService.queryGoodsByGoodsId(goodsId);
//
//        int miaoshaStatus=0;//秒杀倒计时  秒杀进行中  秒杀已结束
//
//        long start = goods.getStartTime().getTime();//开始时间
//        long end = goods.getEndTime().getTime();//结束时间
//        long now = System.currentTimeMillis();//系统当前时间
//        long remainSeconds =0;//秒杀开始的剩余时间
//        if (now<start){//未开始
//            miaoshaStatus=0;
//            remainSeconds=(start-now)/1000;
//        }else if (now>end){//秒杀结束
//            miaoshaStatus=2;
//            remainSeconds=-1;
//        }else {//秒杀正在进行中
//            miaoshaStatus=1;
//            remainSeconds=0;
//        }
//        model.addAttribute("goods",goods);
//        model.addAttribute("user",userEntity);
//        model.addAttribute("miaoshaStatus",miaoshaStatus);
//        model.addAttribute("remainSeconds",remainSeconds);
//        return "goods_detail";
//    }






}
